using System;
using System.Collections;
using System.Web;
using Sedna.Core.Controller.Configurations;
using Sedna.Core.Security;

namespace Sedna.Core.Controller.Menu
{
	public class MenuItem : GenericConfiguration, IMenuItem
	{
		private IList menuItems = new ArrayList();
		private bool isDefault = false;
		private bool isStatic = false;

		private static int lastId = 0;

		private static MenuItem empty = new MenuItem();

		public MenuItem()
		{
			Id = "menu_" + (++lastId);
		}

		public IList MenuItems
		{
			get { return menuItems; }
			set { menuItems = value; }
		}

		public bool IsDefault
		{
			get { return isDefault; }
			set { isDefault = value; }
		}

		public bool IsStatic
		{
			get { return isStatic; }
			set { isStatic = value; }
		}

		public IMenuItem Empty
		{
			get
			{
				return empty;
			}
		}


		public IMenuItem GetMenuItemById(string id)
		{
			if(Id == id)
			{
				return this;
			}
			if(menuItems == null)
			{
				return null;
			}
			foreach(IMenuItem menuItem in menuItems)
			{
				if(menuItem.Id == id)
				{
					return menuItem;
				}
				IMenuItem tmpMenuItem = menuItem.GetMenuItemById(id);
				if(tmpMenuItem != null)
				{
					return tmpMenuItem;
				}
			}
			return null;
		}

		public IMenuItem GetDefaultMenuItem()
		{
			if(menuItems == null || menuItems.Count == 0)
			{
				return null;
			}
			foreach(MenuItem menuItem in menuItems)
			{
				if(menuItem.IsDefault && menuItem.IsVisibleForPrincipal() && menuItem.IsEnabledForPrincipal())
				{
					return menuItem;
				}
			}
			foreach(MenuItem menuItem in menuItems)
			{
				if(menuItem.IsVisibleForPrincipal() && menuItem.IsEnabledForPrincipal() && !menuItem.IsStatic)
				{
					return menuItem;
				}
			}
			return null;
		}


		public virtual void LoadMenuItems(HttpContext httpContext, IExecutionContext executionContext, string executionContextPrefix)
		{
			return;
		}

	}
}
